/*
	Copyright (c) 2011 Canadensys
*/
package net.canadensys.dataportal.vascan.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.canadensys.dataportal.vascan.config.impl.InstallationConfig;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

/**
 * This servlet is used to download a generated file from the server disk.
 * The file must reside in the InstallationConfig.GENERATED_CONTENT_DIR folder.
 */
public class GetFileServlet extends HttpServlet {
	
	private static final long serialVersionUID = -2583264069960028504L;
	
	private static final String ZIP_EXT = "zip";
	private static final String TXT_EXT = "txt";
	
	private static final String ZIP_MIME_TYPE = "application/zip";
	private static final String TXT_MIME_TYPE = "text/plain";
	
	/**
	 * Servlet to handle the get of a generated file on the server.
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 
		String fileName = req.getParameter("q");
		
		if(fileName == null || fileName.equals("")){
			return;
		}
		//make sure to keep only the file name
		fileName = FilenameUtils.getName(fileName);
		
		String generatedContentPath = InstallationConfig.getInstance().get(InstallationConfig.GENERATED_CONTENT_DIR_KEY);
		File wantedFile = new File(generatedContentPath + fileName);
		
		if(!wantedFile.exists()){
			res.getWriter().write(fileName + " not found");
			return;
		}
		
		try{
			FileInputStream istrm = new FileInputStream(wantedFile);
			if(ZIP_EXT.equalsIgnoreCase(FilenameUtils.getExtension(fileName))){
				res.setContentType (ZIP_MIME_TYPE);
			}
			else if(TXT_EXT.equalsIgnoreCase(FilenameUtils.getExtension(fileName))){
				res.setContentType (TXT_MIME_TYPE);
			}
			else{
				res.getWriter().write(fileName + " unknown extension");
				return;
			}
			
			res.setHeader ("Content-Disposition", "attachment; filename=\""+fileName+"\"");
			int byteCopied = IOUtils.copy(istrm, res.getOutputStream());
			res.setContentLength(byteCopied);
		}
		catch(IOException ioEx){
			Logger.getLogger(getClass().getName()).severe("Error while trying to get file " + wantedFile.getAbsolutePath());
		}
	}
}
